package com.demo.study.base.demos;

import lombok.AllArgsConstructor;

/**
 * @author baymax
 * @since 2025-07-24
 */
public class Demo6_Copy {
    public static void main(String[] args) throws CloneNotSupportedException {
        Person p1 = new Person("张三", 18, new Address("安徽省合肥市"), new Hobby("唱歌"));
        Person p2 = p1;
        Person p3 = p1.clone();
        System.out.println(p1 == p2); // true
        System.out.println(p1 == p3); // false
        System.out.println(p1.name == p3.name); // true
        System.out.println(p1.age == p3.age); // true
        System.out.println(p1.address == p3.address); // 浅拷贝true
        System.out.println(p1.hobby == p3.hobby); // 深拷贝false
    }

}

@AllArgsConstructor
class Person implements Cloneable {
    String name;
    int age;
    Address address;
    Hobby hobby;

    @Override
    protected Person clone() throws CloneNotSupportedException {
        Person clone = (Person) super.clone(); // 默认

        // 是浅拷贝
        clone.hobby = this.hobby.clone(); // 深拷贝
        return clone;
    }
}

@AllArgsConstructor
class Address {
    String desc;
}

@AllArgsConstructor
class Hobby implements Cloneable {
    String desc;

    @Override
    protected Hobby clone() throws CloneNotSupportedException {
        return (Hobby) super.clone();
    }
}
